﻿using System;
using System.Collections.Generic;
using System.Text;
using SimpleUnitity.Database.Extension;
using SimpleUnitity.Database.Config;
using System.Configuration;
using SimpleUnitity.Log;
using SimpleUnitity.Database;
using SimpleUnitity.Cache;

namespace SimpleUnitity
{
    public static class UnitityHelper
    {
        public static IDictionary<string, string> ParseConfig(string configValue)
        {
            IDictionary<string, string> configs = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);
            if (string.IsNullOrEmpty(configValue))
            {
                return configs;
            }

            string[] items = configValue.Split(';');
            foreach (var item in items)
            {
                var prop = item.Split('=');
                if (prop.Length == 2)
                {
                    configs.Add(prop[0], prop[1]);
                }
            }
            return configs;
        }

        private static void SaveDataHelperToCache(string name, DbProviderSection section, ILog log, string connectionString, bool sync)
        {
            ICache cache = new NormalCache(true);
            cache.Set("Section", section);
            cache.Set("ConnectionString", connectionString);
            cache.Set("Log", log);
            cache.Set("SyncLog", sync);
            helperCache.Set("DataHelper_" + name, cache);
        }

        private static DataHelper GetDataHelperFromCache(string name)
        {
            DataHelper db = null;
            ICache cache = helperCache.Get("DataHelper_" + name) as ICache;
            if (cache != null)
            {
                DbProviderSection section = cache.Get("Section") as DbProviderSection;
                string connectionString = cache.Get("ConnectionString") as string;
                ILog log = cache.Get("Log") as ILog;
                bool sync = (bool)cache.Get("SyncLog");
                var tools = section.CreateDbTool(connectionString);
                db = new DataHelper(tools, log);
                db.SyncLog = sync;
                db.IdentitySQL = section.IdentitySQL;
            }
            return db;
        }

        //ProviderSection=dbproviders/sqlserver;ConnectionStringName=MySQL;LogPath=d:/log/MySQL;TimeMode=Hour
        static ICache helperCache = new NormalCache();
        public static DataHelper ParseDataHelper(string configs)
        {
            DataHelper db = null;
            IDictionary<String, string> dbconfigs = ParseConfig(configs);
            if (dbconfigs.ContainsKey("Name"))
            {
                db = GetDataHelperFromCache(dbconfigs["Name"]);
                if (db != null)
                {
                    return db;
                }
            }

            ILog dblog = null;
            DbProviderSection section = (DbProviderSection)ConfigurationManager.GetSection(dbconfigs["ProviderSection"]);
            string connName = dbconfigs["ConnectionStringName"];
            string connString = ConfigurationManager.ConnectionStrings[connName].ConnectionString;
            if (dbconfigs.ContainsKey("LogPath"))
            {
                PerTimeType perTimeType = PerTimeType.Hour;
                if (dbconfigs.ContainsKey("TimeMode"))
                {
                    perTimeType = (PerTimeType)Enum.Parse(typeof(PerTimeType), dbconfigs["TimeMode"]);
                }
                dblog = new PerTimeFileLog(dbconfigs["LogPath"], perTimeType);
            }
            else if (dbconfigs.ContainsKey("LogFile"))
            {
                dblog = new FileLog(dbconfigs["LogFile"]);
            }
            DbTool dbtools = section.CreateDbTool(connString);
            db = new DataHelper(dbtools, dblog);
            db.IdentitySQL = section.IdentitySQL;
            if (dbconfigs.ContainsKey("synclog"))
            {
                if (string.Equals(dbconfigs["synclog"], "true", StringComparison.CurrentCultureIgnoreCase))
                {
                    db.SyncLog = true;
                }
            }
            if (dbconfigs.ContainsKey("Name"))
            {
                SaveDataHelperToCache(dbconfigs["Name"], section, dblog, connString, db.SyncLog);
            }
            return db;
        }
    }
}
